﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Jinndev.Async {

    public class ActionTaskQueue : TaskQueue {

        private List<Action> actionList = new List<Action>();
        private int index;

        public ActionTaskQueue(string description) : base(description) {

        }

        public ActionTaskQueue(string description, params Action[] actions) : base(description) {
            if (actions != null) {
                actionList.AddRange(actions);
            }
        }

        public ActionTaskQueue(string description, Action action, params Action[] actions) : base(description) {
            if(action != null) {
                actionList.Add(action);
            }
            if (actions != null) {
                actionList.AddRange(actions);
            }
        }

        public void Add(Action action) {
            actionList.Add(action);
        }

        public override bool HasNext() {
            return index < actionList.Count;
        }

        public async override Task InvokeNextAsync() {
            if (HasNext()) {
                Action action = actionList[index++];
                Task task = new Task(action);
                task.RunSynchronously();
                await task;
            }
        }

        public override void InvokeNext() {
            if (HasNext()) {
                Action action = actionList[index++];
                action.Invoke();
            }
        }

        public override float GetProgress() {
            if (actionList.Count > 0) {
                return (float)index / actionList.Count;
            }
            return 1;
        }

        public override int GetCount() {
            return actionList.Count;
        }

    }

}
